package game.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import common.config.exception.CustomException;
import common.model.enums.ProductUnlockTypeEnum;
import common.model.po.GBuilding;
import common.model.po.GItem;
import common.model.po.GProductUnlock;
import game.mapper.GProductUnlockMapper;
import game.model.converter.GProductUnlockConverter;
import game.model.vo.ProductUnlockVo;
import game.service.GBuildingService;
import game.service.GItemService;
import game.service.GProductUnlockService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author 米泽鹏
 * @since 2024-01-24 下午 07:10
 */
@Service
public class GProductUnlockServiceImpl extends ServiceImpl<GProductUnlockMapper, GProductUnlock> implements GProductUnlockService {

	@Resource
	private GProductUnlockMapper mapper;
	@Resource
	private GItemService itemService;
	@Resource
	private GBuildingService buildingService;

	@Override
	public List<ProductUnlockVo> getAllProductUnlockVoByProductId(Long productId) {
		List<GProductUnlock> unlockList = lambdaQuery().eq(GProductUnlock::getProductId, productId).list();
		List<ProductUnlockVo> unlockVoList = Lists.newArrayListWithCapacity(unlockList.size());
		// 查询解锁项中的所有物品和建筑
		Set<Long> itemIdSet = unlockList.stream().filter(unlock -> unlock.getType() == ProductUnlockTypeEnum.ITEM).map(GProductUnlock::getElementId).collect(Collectors.toSet());
		Set<Long> buildingIdSet = unlockList.stream().filter(unlock -> unlock.getType() == ProductUnlockTypeEnum.BUILDING).map(GProductUnlock::getElementId).collect(Collectors.toSet());
		List<GItem> itemList = itemIdSet.isEmpty() ? Collections.emptyList() : itemService.listByIds(itemIdSet);
		List<GBuilding> buildingList = buildingIdSet.isEmpty() ? Collections.emptyList() : buildingService.listByIds(buildingIdSet);
		// 转换为vo（处理image字段）
		for (GProductUnlock unlock : unlockList) {
			ProductUnlockVo productUnlockVo = GProductUnlockConverter.poToVo(unlock);
			ProductUnlockTypeEnum unlockType = unlock.getType();
			switch (unlockType) {
				case ITEM:
					GItem item = itemList.stream().filter(i -> i.getId().equals(unlock.getElementId())).findFirst().orElseThrow(() -> new CustomException("物品不存在"));
					productUnlockVo.setImage(item.getImage());
					break;
				case BUILDING:
					GBuilding building = buildingList.stream().filter(i -> i.getId().equals(unlock.getElementId())).findFirst().orElseThrow(() -> new CustomException("建筑不存在"));
					productUnlockVo.setImage(building.getImage());
					break;
				default:
					break;
			}
			unlockVoList.add(productUnlockVo);
		}
		return unlockVoList;
	}

}
